import React, { Component, } from 'react';
import { StyleSheet, View, AsyncStorage, } from 'react-native';
import BaseSelector from '../../app/selectors/base';
import * as BaseActions from '../../app/actions/base';
import AuthSelector from '../../app/selectors/auth';
import OpenAccountSelector from '../../app/selectors/openAccount';
import DealOutSelector from '../../app/selectors/dealOut';
import connect from '../../app/store/connect';
import HomeTopCard from './components/topcard';
import IconContainer from '../../components/KingKong/icon-container';
import { itemConfig, } from './config/itemConfig';
import { getToken, } from '../../commons/utils/passport';
import { POST, GET, } from '../../commons/utils/request';
import urls from '../../app/constants/urls';
import Toast from '../../components/Toast';

const styles = StyleSheet.create({
  container:
  {
    flex: 1,
  },
  headerButton: {
    borderRadius: 5,
    borderWidth: 3,
    borderColor: '#B0B0B0',
    backgroundColor: '#B0B0B0',
    margin: 10,
    padding: 10,
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
  },
  itemContainer: {
    marginTop: 100,
    marginBottom: 100,
  },
  dataPicker: {
    marginLeft: 40,
    paddingTop: 20,
    paddingBottom: 10,
    color: '#212121',
    fontSize: 14,
    textAlign: 'left',
  },
});

@connect(BaseSelector, BaseActions)
@connect(AuthSelector, BaseActions)
@connect(OpenAccountSelector, BaseActions)
@connect(DealOutSelector, BaseActions)
export default class Home extends Component {
  static navigationOptions = {
    headerTitle: '首页',
  };

  constructor(props) {
    super(props);
    this.state = {
      status: -1,
      balance: 0,
      refresh: false,
      isLogin: false,
      cityRefresh: false,
      refreshWhenNextLogin: false,
    };
  }

  async componentWillMount() {
    const token = await getToken()
    this.props.actions.login({isLogin: token != null})
    this.getAccountInfo(token);
  }

  componentDidMount() {
    console.log('TAGGG', `===home===componentDidMount==City====`);
    // this.props.actions.getCityList()
    // this.props.actions.getCountryList()
    if(!this.state.cityRefresh) {
      GET(urls.countryInfo, {}).then(async resp => {
          await AsyncStorage.setItem('countryInfo', JSON.stringify(resp.data))
          if(!this.state.cityRefresh) {
            this.setState({cityRefresh: true})
          }
      }, error => {
        console.log('TAGGG', `isCountryList====error==${JSON.stringify(error)}`);
      });
      GET(urls.cityInfo, {}, null).then(async resp => {
          console.log('TAGGG', `cityInfo====resp==${JSON.stringify(resp)}`);
          await AsyncStorage.setItem('cityInfo',JSON.stringify(resp.data))
          if(!this.state.cityRefresh) {
            this.setState({cityRefresh: true})
          }
      }, error => {
        console.log('TAGGG', `cityInfo====error==${JSON.stringify(error)}`);
      });
    }
  }

  async getAccountInfo(token, ) {
    if (!token) {
      return;
    }
    await POST(urls.accountInfo, JSON.stringify('')).then(resp => {
      console.log('TAGGG', `===home===getAccountInfo====resp==${JSON.stringify(resp)}`);
      if (resp && resp.code == 0 && resp.data) {
        const status = resp.data.status;
        const balance = resp.data.balance || 0;
        const { _status, _balance } = this.state
        if(status == _status && balance == _balance) {
          return
        }
        this.setState({ status, balance, });
      }
    });
  }

  async getAccountInfoWhenLoged() {
    const { logged, authed, hasOpenAccount, dealTime, } = this.props;
    console.log('TAGGG', `===home===getAccountInfoWhenLoged====logged====` + logged + '===authed===' + authed + ',====hasOpenAccount===' + hasOpenAccount + '===dealTime===' + dealTime);
    if (!logged) {
      if(this.state.status != 0 || this.state.balance != 0) {
        this.setState({ status: 0, balance: 0,});
        return;
      }
      if (authed || hasOpenAccount) {
        this.setState({ refreshWhenNextLogin: true, });
      }
    }
    if(this.state.refreshWhenNextLogin) {
      const token = await getToken()
      this.getAccountInfo(token);
      this.setState({ refreshWhenNextLogin: false, });
      return
    }
    if(dealTime && dealTime.length > 0) {
      console.log('TAGGG', `===home===getAccountInfoWhenLoged====dealTime====` + dealTime);
      const token = await getToken()
      this.getAccountInfo(token);
      this.props.actions.dealOut({dealTime: ''})
    }
    if(this.state.status == 1) {
      return
    }
    if(this.state.status < 0) {
      const token = await getToken()
      this.getAccountInfo(token);
      return
    }
    if(this.state.status == 2 && authed) {
      const token = await getToken()
      this.getAccountInfo(token);
      return
    }
    if(this.state.status == 0 && hasOpenAccount) {
      const token = await getToken()
      this.getAccountInfo(token);
    }
  }

  onPress = async (jumpUrl) => {
    const { logged } = this.props
    if(!logged) {
      this.props.navigation.navigate('Login');
      return
    }
    if(this.state.status == 2) {
      this.props.navigation.navigate('Account');
      this.setState({ hasRequestUserInfo: false });
      return
    }
    if(this.state.status == 0) {
      this.props.navigation.navigate('OpenAccount');
      this.setState({ refreshAccountnfo: true });
      return
    }
    this.props.navigation.navigate(jumpUrl);
  };

  onHomeCardPress = (status) => {
    const { logged } = this.props
    if(!logged) {
      this.props.navigation.navigate('Login');
      return
    }
    if(status == 0) {
      this.props.navigation.navigate('OpenAccount');
    }
    if(status == 1) {
      Toast.show({ title: '您的账户总额:' + this.state.balance + '元', });
    }
    if(status == 2) {
      this.props.navigation.navigate('Account');
    }
  };

  render() {
    this.getAccountInfoWhenLoged()
    const topCardInfo = {
      status: this.state.status,
      balance: this.state.balance,
    };
    const { logged, authed, hasOpenAccount } = this.props
    console.log('TAGGG', `=====home====render====topCardInfo==${logged}==='=authed===${authed}====hasOpenAccount===${hasOpenAccount}`);
    return (
      <View style={styles.container}>
        <HomeTopCard dataSource={topCardInfo}  onPress={this.onHomeCardPress} />
        <IconContainer style={styles.itemContainer} dataSource={itemConfig} onPress={this.onPress} />
      </View>
    );
  }
}
